<template>
  <view
    class="kk-container"
    :style="{
      background: pageBackground,
      height: containerHeight,
    }"
    @touchstart="touchstart"
    @touchend="touchend"
  >
    <!-- @touchstart.stop.prevent="touchstart"
    @touchend.stop.prevent="touchend" -->

    <PrivacyPopup v-if="isShowPrivacyPopup"></PrivacyPopup>
    <kkLoading v-if="showLoading" />
    <header
      class="kk-container-header"
      :style="{
        height: `calc(${headerHeight})`,
        background: headerBackgroundColor,
      }"
    >
      <slot name="header">
        <KKNavBar
          :title="title"
          :isShowHeader="isShowHeader"
          :isSelfHandleBackAction="isSelfHandleBackAction"
          :isShowleftIcon="isShowleftIcon"
          :headerBackgroundColor="headerBackgroundColor"
          :titleColor="titleColor"
          :backRoute="backRoute"
          @navigateBack="navigateBack"
        >
        </KKNavBar>
      </slot>
      <slot name="expand"></slot>
    </header>
    <main class="kk-container-main">
      <scroll-view
        id="scrollview"
        scroll-y="true"
        :style="{
          height: `100%`,
          '-webkit-overflow-scrolling': 'touch',
        }"
        refresher-background="transparent"
        :scroll-with-animation="scrollAnimation"
        :refresher-enabled="refresherEnabled"
        :refresher-triggered="triggered"
        :scroll-top="scrollTop"
        @refresherpulling="onRefresherPulling"
        @scroll="handlerScroll"
        @scrolltolower="handlerScrolltolower"
        @refresherrefresh="handlerRefresherrefresh"
      >
        <!-- 自定义下拉刷新内容 -->
        <view class="refresher" v-if="refresherStatus === 'refreshing'">
          <up-loading-icon
            text="加载中..."
            textSize="14"
            vertical="true"
            textColor="#999999"
          ></up-loading-icon>
        </view>
        <view v-if="showPageLoading" class="pageLoading">
          <image
            class="pageLoading-icon"
            src="@/static/images/common/loading.png"
          ></image>
          <view class="pageLoading-text"> 加载中... </view>
          <!-- <up-loading-icon
            text=""
            textSize="14"
            vertical="true"
            textColor="#999999"
          ></up-loading-icon> -->
        </view>
        <slot> </slot>
        <view
          class="kk-container-reachBottom"
          v-if="loadMoreStatus === 'no-more'"
          :style="'margin-top:' + loadMoreMarginTop + 'rpx'"
        >
          {{ contentText.contentnomore }}
        </view>
        <up-loadmore
          class="kk-container-loadingMore"
          v-if="loadMoreStatus === 'loading'"
          :style="'margin-top:' + loadMoreMarginTop + 'rpx'"
          status="loading"
          :loading-text="contentText.contentrefresh"
        />
      </scroll-view>
    </main>
    <footer
      class="kk-container-footer"
      :style="{
        height: $slots.footer ? footerHeightCalc : '',
        background: footerBackground,
      }"
    >
      <slot name="footer"></slot>
      <view
        class="kk-container-footer-customFooter"
        v-if="isShowCustomFooter"
        :style="{ height: footerHeightCalc }"
      >
        <slot name="customFooter"></slot>
      </view>
    </footer>
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { kkSliderDirection } from "../enmu";
import KKNavBar from "../KKNavBar/index.vue";
import kkLoading from "./loading.vue";
import PrivacyPopup from "@/components/privacy-popup/index.vue";
import { onShow } from "@dcloudio/uni-app";
import { getKKToken } from "@/utils/storageUtil";
import { jumpLoginPage } from "@/utils/util";

const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  titleColor: {
    type: String,
    default: "",
  },
  // 是否显示header头
  isShowHeader: {
    type: Boolean,
    default: false,
  },
  // 是否显示左侧 icon
  isShowleftIcon: {
    type: Boolean,
    default: true,
  },
  // 回退页面的路由
  backRoute: {
    type: String,
    default: "",
  },
  // 滚动是否开启动画
  scrollAnimation: {
    type: Boolean,
    default: true,
  },
  // 是否开启下拉刷新
  refresherEnabled: {
    type: Boolean,
    default: true,
  },
  // 是否开启滑动放心监听
  touchEnable: {
    type: Boolean,
    default: false,
  },
  // 是否开启滚动监听
  scrollEnabled: {
    type: Boolean,
    default: false,
  },
  // 页面的背景色
  pageBackground: {
    type: String || null,
    default: "#F7F7F7",
  },
  // 顶部背景颜色
  headerBackgroundColor: {
    type: String || null,
    default: "#ffffff",
  },
  marginBottom: {
    type: Number,
    default: 0,
  },
  scrollPaddingTop: {
    // 中间滑动区域顶部间隙
    type: Number,
    default: 0,
  },
  // 是否显示自定义 footer
  isShowCustomFooter: {
    type: Boolean,
    default: false,
  },
  // 距底部的距离
  footerHeight: {
    type: Number,
    default: 100,
  },
  // footer 背景颜色
  footerBackground: {
    type: String || null,
    default: "#fff",
  },
  // 加载更多状态 loading: 加载中 no-more: 没有更多加载完成
  loadMoreStatus: {
    type: String,
    default: "",
  },
  // 加载更多顶部偏移 单位rpx
  loadMoreMarginTop: {
    type: Number,
    default: 30,
  },
  // 显示loading
  showLoading: {
    type: Boolean,
    default: false,
  },
  // 显示页面Loading
  showPageLoading: {
    type: Boolean,
    default: false,
  },
  // 是否显示隐私协议弹窗
  isShowPrivacyPopup: {
    type: Boolean,
    default: true,
  },
  scrollId: {
    type: String,
    default: undefined,
  },
  isSelfHandleBackAction: {
    type: Boolean,
    default: false,
  },
});

const touchData = ref({}); //滑动事件数据
const triggered = ref(false);
const scrollTop = ref(0);
const parallaxScroll = ref(0);
const contentText = ref({
  contentrefresh: "拼命加载中～",
  contentnomore: "我们也是有底线的噢～",
});

const containerHeight = computed(() => {
  return "100vh";
});
const headerHeight = computed(() => {
  return "auto";
});

//底部容器的高度
// uni.upx2px
const footerHeightCalc = computed(() => {
  return `calc(${props.footerHeight}rpx + env(safe-area-inset-bottom))`;
});

const setScrollTop = (value: number) => {
  scrollTop.value = value;
};

const handlerScroll = (e: any) => {
  if (!props.scrollEnabled) return;
  const { scrollTop } = e.detail;
  parallaxScroll.value = scrollTop;
  emit("handlerScroll", scrollTop);
};

// 滚动到页面底部
const handlerScrolltolower = () => {
  uni.$emit("onReachBottom");
  emit("handlerReachBottom");
};

const refresherStatus = ref("normal");
// 组件下拉执行
const handlerRefresherrefresh = () => {
  triggered.value = true;
  setTimeout(() => {
    refresherStatus.value = "normal";
    triggered.value = false;
  }, 1000);
  emit("handlerRefresh");
  uni.$emit("onPullDownRefresh");
};

const onRefresherPulling = () => {
  // refresherStatus.value = "refreshing";
};

const touchstart = (e: any) => {
  if (!props.touchEnable) {
    return;
  }
  if (e.changedTouches && e.changedTouches.length > 0) {
    touchData.value.clientX = e.changedTouches[0].clientX;
    touchData.value.clientY = e.changedTouches[0].clientY;
  }
};

const sliderDirectionDeltaValue = 30;
const touchend = (e: any) => {
  if (!props.touchEnable) {
    return;
  }
  if (e.changedTouches && e.changedTouches.length > 0) {
    const subX = e.changedTouches[0].clientX - touchData.value.clientX;
    const subY = e.changedTouches[0].clientY - touchData.value.clientY;
    if (subY > sliderDirectionDeltaValue) {
      //下滑
      emit("slideDirection", kkSliderDirection.down);
    }
    if (subY < -1 * sliderDirectionDeltaValue) {
      //上滑
      emit("slideDirection", kkSliderDirection.up);
    }
    if (subX > sliderDirectionDeltaValue && Math.abs(subY) <= 30) {
      // 左滑
      emit("slideDirection", kkSliderDirection.left);
    }
    if (subX < -1 * sliderDirectionDeltaValue && Math.abs(subY) <= 30) {
      // 右滑
      emit("slideDirection", kkSliderDirection.right);
    }
  }
};

const navigateBack = () => {
  emit("navigateBack");
};

onShow(() => {
  if (!getKKToken()) {
    jumpLoginPage();
  }
});

const emit = defineEmits([
  "handlerScroll",
  "handlerReachBottom",
  "handlerRefresh",
  "slideDirection",
  "navigateBack",
]);
defineExpose({ setScrollTop });
</script>

<style lang="scss">
.kk-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;

  &-header {
    z-index: 10;
    position: relative;
    background: #fff;
  }
  &-main {
    z-index: 10;
    flex: 1;
    overflow: auto;
    position: relative;
    margin-bottom: 0rpx;
  }
  &-reachBottom {
    display: flex;
    flex-flow: row;
    justify-content: center;
    align-items: center;
    margin-bottom: 30rpx;
    height: 33rpx;
    font-size: 24rpx;
    color: #999999;
    line-height: 33rpx;
  }
  &-loadingMore {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-bottom: 30rpx;
  }
  .pageLoading {
    width: 100vw;
    margin-top: 30rpx;
    // height: calc(100% - 306rpx);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    // margin-top: calc(100%);
    &-icon {
      width: 64rpx;
      height: 64rpx;
    }
    &-text {
      padding-top: 20rpx;
      margin-left: 2rpx;
      font-size: 28rpx;
      color: #999999;
      line-height: 34rpx;
      font-weight: 400;
      text-align: center;
    }
  }
  .refresher {
    background: #fff;
    z-index: 999;
    margin-top: -50px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
  }
}
</style>
